﻿using ImageManager.Common;
using ImageManager.DBAccess;
using ImageManager.ImageApi;
using ImageManager.ImageApi.AuthenticationInjection;
using ImageManager.ImageService;
using ImageManager.Model;
using ImageManager.MyExcep;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.Record;

namespace ImageManager.Controllers
{
    public class ImageController : MyBaseController<ImageModel>
    {
        protected override BaseServiceProvider<ImageModel> getSp()
        {
            return ServiceLoader.GetService<ImageServiceProvider>();
        }

        [HttpPost, MyAuthorize(AuthorizeLevelEnum.AllUser)]
        public ResponseData<ImageModel> QueryMyDownload(dynamic qryParam)
        {
            var sp = getSp() as ImageServiceProvider;
            var index = DEF_PAGE_INDEX;
            var pageSize = DEF_PAGE_SIZE;
            if (qryParam?.pageIndex != null)
                int.TryParse(qryParam?.pageIndex?.ToString(), out index);
            if (qryParam?.pageIndex != null)
                int.TryParse(qryParam?.pageSize?.ToString(), out pageSize);
            var cond = QueryConditionResolver.Resolver<ImageModel>(qryParam);
            var datAsDic = qryParam as JObject;
            string startDate = DateTime.MinValue.ToString();
            string endDate = DateTime.MaxValue.ToString();
            var dt = DateTime.Now;
            if (datAsDic != null)
            {
                if (datAsDic.ContainsKey("S_DW_STARTDATE"))
                {
                    if (DateTime.TryParse(datAsDic["S_DW_STARTDATE"].ToString(), out dt))
                    {
                        startDate = dt.ToString("yyyy-MM-dd 00:00:00");
                    }
                }
                if (datAsDic.ContainsKey("S_DW_ENDDATE"))
                {
                    if (DateTime.TryParse(datAsDic["S_DW_ENDDATE"].ToString(), out dt))
                    {
                        endDate = dt.ToString("yyyy-MM-dd 23:59:59");
                    }
                }
            }
            int total = 0;
            var result = new ResponseData<ImageModel>(sp.ListMyDownload(cond, startDate, endDate, index, pageSize, out total));
            result.TotalCount = total;
            return result;
        }
        [HttpPost, MyAuthorize(AuthorizeLevelEnum.AllUser)]
        public ResponseData<ImageModel> Upload(IFormFile file)
        {
            if (file.Length == 0) throw new MyArgException();
            var service = getSp() as ImageServiceProvider;
            var stream = file.OpenReadStream();
            var imageModel = service!.CreateByImage(stream,file.ContentType.StartsWith("video"));
            imageModel.ImageName = file.FileName;
            imageModel.FileType = file.ContentType;
            imageModel.Size = file.Length;
            service.Save(imageModel);
            var result = new ResponseData<ImageModel>(imageModel);
            return result;
        }
        [HttpGet, MyAuthorize(AuthorizeLevelEnum.AllUser)]
        public FileContentResult Download(string pk)
        {
            var service = getSp() as ImageServiceProvider;
            var model = service!.Get(pk);
            var downloadHistory = new DownloadHistoryModel();
            downloadHistory.Image = pk;
            downloadHistory.Pay = model.Price;
            var dwSp = ServiceLoader.GetService<DownloadHistoryServiceProvider>();
            dwSp.Save(downloadHistory);
            using (var stream = service.Download(model))
            {
                var bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                return new FileContentResult(bytes,model.FileType);
            }
        }
        [HttpGet]
        public FileContentResult Thumbnail(string pk)
        {
            var service = getSp() as ImageServiceProvider;
            var model = service!.Get(pk);
            if (model.FileType.StartsWith("video")) throw new MyDataOptException();
            using (var stream = service.Thumbnail(model))
            {
                var bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                return new FileContentResult(bytes, "image/jpeg");
            }
        }
        [HttpGet]
        public FileContentResult Preview(string pk)
        {
            var service = getSp() as ImageServiceProvider;
            var model = service!.Get(pk);
            if (model.FileType.StartsWith("video")) throw new MyDataOptException();
            using (var stream = service.Preview(model))
            {
                var bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                return new FileContentResult(bytes, "image/jpeg");
            }
        }

        [HttpGet]
        public FileContentResult Excel(string period)
        {
            var service = getSp() as ImageServiceProvider;
            using (var excel = service.ToExcel(period))
            {
                excel.Seek(0,SeekOrigin.Begin);
                var bytes = new byte[excel.Length];
                excel.Read(bytes, 0, bytes.Length);
                var r = new FileContentResult(bytes, "application/vnd.ms-excel");
                r.FileDownloadName = "上传清单"+ period + ".xls";
                return r;
            }
        }
    }
}
